<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="名称" v-bind="validateInfos.name">
            <a-input v-model:value="formData.name" placeholder="请输入名称" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="价格" v-bind="validateInfos.price">
            <a-input-number v-model:value="formData.price" placeholder="请输入价格" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="类型" v-bind="validateInfos.type">
            <a-input-group compact>
              <a-input 
                v-model:value="formData.type" 
                placeholder="请输入类型" 
                :disabled="disabled" 
                style="width: calc(100% - 100px)"
              />
              <a-button 
                type="primary" 
                :disabled="disabled || !formData.type" 
                @click="handleGenerateCode"
                :loading="generatingCode"
                style="width: 100px"
              >
                生成编号
              </a-button>
            </a-input-group>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="编号" v-bind="validateInfos.code">
            <a-input v-model:value="formData.code" placeholder="请输入编号" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否默认" v-bind="validateInfos.isDefault">
            <JDictSelectTag v-model:value="formData.isDefault" dictCode="yes_no" placeholder="请选择是否默认" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="医院" v-bind="validateInfos.hospital_id">
            <a-select
              v-model:value="formData.hospital_id"
              placeholder="请输入医院名称搜索"
              :disabled="disabled"
              :options="hospitalOptions"
              :field-names="{ label: 'label', value: 'value' }"
              show-search
              :filter-option="filterHospitalOption"
              allow-clear
              :option-filter-prop="'label'"
              @change="handleHospitalChange"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate, list, getMaxCode } from '../StandardPrice.api';
  import { Form } from 'ant-design-vue';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { defHttp } from '/@/utils/http/axios';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formBpm: { type: Boolean, default: true },
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);

  const formData = reactive<Record<string, any>>({
    id: '',
    name: '',
    price: undefined,
    type: '',
    code: '',
    isDefault: '',
    hospital_id: undefined,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const hospitalOptions = ref<any[]>([]);
  const generatingCode = ref<boolean>(false);
  
  //表单验证
  const validatorRules = {};
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  
  // 医院选项搜索过滤函数
  function filterHospitalOption(input: string, option: any) {
    if (!input) {
      return true;
    }
    const searchText = input.toLowerCase().trim();
    const hospitalName = (option?.label || '').toLowerCase();
    const hospitalValue = String(option?.value || '').toLowerCase();
    
    // 支持按医院名称或ID搜索
    return hospitalName.includes(searchText) || hospitalValue.includes(searchText);
  }
  
  // 医院选择改变时的处理
  function handleHospitalChange(value: any) {
    // 当用户清除选择时，value 为 undefined
    // 确保 formData.hospital_id 被正确设置为 undefined
    if (value === undefined || value === null || value === '') {
      formData.hospital_id = undefined;
    }
  }
  
  // 加载医院选项（获取全部医院，不添加任何过滤参数）
  async function loadHospitalOptions() {
    try {
      const result = await defHttp.get({
        url: '/nurse_hospital/nurseHospital/rootList',
        params: {
          pageNo: 1,
          pageSize: 99999,
        },
      });
      if (result && result.records && Array.isArray(result.records)) {
        hospitalOptions.value = result.records.map((item) => ({
          value: item.id,
          label: item.name,
        }));
      } else {
        hospitalOptions.value = [];
      }
    } catch (error) {
      createMessage.error('加载医院选项失败，请刷新重试');
      hospitalOptions.value = [];
    }
  }

  const disabled = computed(() => {
    return props.formDisabled;
  });
  
  /**
   * 解析编码，提取 A 部分
   * @param code 编码字符串，可能是 "A-B" 或 "A" 形式
   * @returns A 部分的数值，如果格式不正确返回 null
   */
  function extractCodeA(code: string): number | null {
    if (!code || typeof code !== 'string') {
      return null;
    }
    
    // 如果包含 "-"，则是 A-B 形式，取 A
    if (code.includes('-')) {
      const parts = code.split('-');
      const a = parseInt(parts[0], 10);
      return isNaN(a) ? null : a;
    } else {
      // 否则是 A 形式，直接解析
      const a = parseInt(code, 10);
      return isNaN(a) ? null : a;
    }
  }
  
  /**
   * 生成编码
   * 点击"生成编号"按钮时，根据类型生成编号
   */
  async function handleGenerateCode() {
    if (!formData.type || !formData.type.trim()) {
      createMessage.warning('请先输入类型');
      return;
    }
    
    generatingCode.value = true;
    try {
      // 1. 查询同类型的数据
      const sameTypeResult = await list({
        type: formData.type.trim(),
        pageNo: 1,
        pageSize: 9999,
      });
      
      let sameTypeList = sameTypeResult?.records || sameTypeResult?.list || [];
      
      // 如果是编辑模式，排除当前记录（避免把自己算进去）
      if (formData.id) {
        sameTypeList = sameTypeList.filter(item => item.id !== formData.id);
      }
      
      const N = Array.isArray(sameTypeList) ? sameTypeList.length : 0;
      
      let newCode = '';
      
      if (N === 0) {
        // 无同类型数据
        // 调用 maxCode 接口获取最大编码
        const maxCodeResult = await getMaxCode();
        const m = maxCodeResult?.result || maxCodeResult || 0; // 假设接口返回数字
        
        // A = m + 1, B = 1
        const newA = (typeof m === 'number' ? m : parseInt(m, 10) || 0) + 1;
        newCode = `${newA}-1`;
      } else {
        // N > 0，有同类型数据
        // B = N + 1
        const newB = N + 1;
        
        // A 根据返回的编号取一样的数值
        // 取第一条同类型数据的编码
        const firstCode = sameTypeList[0]?.code || '';
        const codeA = extractCodeA(firstCode);
        
        if (codeA !== null) {
          // A 取同类型的编码 A 部分
          newCode = `${codeA}-${newB}`;
        } else {
          // 如果第一条数据编码格式不正确，查找格式正确的编码
          let foundA = null;
          for (const item of sameTypeList) {
            const itemCodeA = extractCodeA(item.code);
            if (itemCodeA !== null) {
              foundA = itemCodeA;
              break;
            }
          }
          
          if (foundA !== null) {
            newCode = `${foundA}-${newB}`;
          } else {
            // 如果所有同类型数据的编码格式都不正确，使用 maxCode 接口
            const maxCodeResult = await getMaxCode();
            const m = maxCodeResult?.result || maxCodeResult || 0;
            const newA = (typeof m === 'number' ? m : parseInt(m, 10) || 0) + 1;
            newCode = `${newA}-${newB}`;
          }
        }
      }
      
      // 将生成的编码填充到编号字段
      if (newCode) {
        formData.code = newCode;
        createMessage.success(`已生成编号: ${newCode}`);
      } else {
        createMessage.warning('生成编号失败，请手动输入');
      }
    } catch (error) {
      createMessage.error('生成编号时出错，请手动输入');
    } finally {
      generatingCode.value = false;
    }
  }

  /**
   * 新增
   */
  async function add() {
    // 先加载医院选项
    await loadHospitalOptions();
    // 重置表单并设置所有字段为初始值（确保 hospital_id 为 undefined）
    nextTick(() => {
      resetFields();
      // 重置 formData，确保所有字段都是初始值
      Object.assign(formData, {
        id: '',
        name: '',
        price: undefined,
        type: '',
        code: '',
        isDefault: '',
        hospital_id: undefined, // 明确设置为 undefined，确保新增时为空
      });
    });
  }

  /**
   * 编辑
   */
  async function edit(record) {
    // 先加载医院选项
    await loadHospitalOptions();
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        // 处理字段名映射：后端返回的 hospitalId 映射到表单的 hospital_id
        if (key === 'hospital_id') {
          // 如果后端返回 hospitalId，使用它（可能为 null）
          if (record.hasOwnProperty('hospitalId')) {
            tmpData.hospital_id = record.hospitalId || undefined; // null 转 undefined，这样表单可以正确显示为空
          } else if (record.hasOwnProperty('hospital_id')) {
            // 兼容 hospital_id 字段
            tmpData.hospital_id = record.hospital_id || undefined;
          } else {
            // 如果没有该字段，明确设置为 undefined，确保表单字段被清除
            tmpData.hospital_id = undefined;
          }
        } else if (record.hasOwnProperty(key)) {
          tmpData[key] = record[key];
        }
      });
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    // 创建表单数据的副本，确保所有字段都被包含
    let model = { ...formData };
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    // 将 hospital_id 转换为 hospitalId（后端期望的字段名）
    const hospitalIdValue = model.hospital_id;
    
    // 严格判断：只有明确有值时才赋值，否则设置为空字符串
    if (hospitalIdValue !== undefined && hospitalIdValue !== null && hospitalIdValue !== '') {
      // 有值，转换为字符串
      model.hospitalId = String(hospitalIdValue);
    } else {
      // 未选择或已清除，必须设置为空字符串
      model.hospitalId = '';
    }
    // 删除原来的 hospital_id 字段
    delete model.hospital_id;
    
    // 确保 hospitalId 确实是空字符串，不能是 null 或 undefined
    if (model.hospitalId === null || model.hospitalId === undefined) {
      model.hospitalId = '';
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    height: 500px !important;
    overflow-y: auto;
    padding: 14px;
  }
</style>
